﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HexParse
{
    public class ClassUartOperation
    {
        System.IO.Ports.SerialPort mySerialPort = new System.IO.Ports.SerialPort();

        public delegate void PushReceiveDataDele(byte[] datas);
        PushReceiveDataDele pushReceiveData;
        
        /// <summary>
        /// 初始化串口
        /// </summary>
        public bool SerialInitial(int BaudRate, System.IO.Ports.Parity Pority, System.IO.Ports.StopBits StopBits, PushReceiveDataDele callback)
        {
            mySerialPort.BaudRate = BaudRate;
            mySerialPort.Parity = Pority;
            mySerialPort.StopBits = StopBits;
            mySerialPort.ReadBufferSize = 12;
            mySerialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(mySerialPort_DataReceived);

            pushReceiveData = callback;

            return true;
        }

        /// <summary>
        /// 打开串口
        /// </summary>
        public bool OpenSerial(string SerialName)
        {
            try
            {
                mySerialPort.PortName = SerialName.Split('(')[1].Split(')')[0];
                mySerialPort.Open();

                return true;
            }
            catch(Exception ex)
            {
                return false;
            }

        }

        /// <summary>
        /// 关闭串口
        /// </summary>
        public bool CloseSerial()
        {
            try
            {
                if(mySerialPort.IsOpen)
                    mySerialPort.Close();

                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        public bool WriteSerialByte(byte[] datas)
        {
            try
            {
                mySerialPort.Write(datas, 0, datas.Length);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 接收导数据
        /// </summary>
        private void mySerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                System.Threading.Thread.Sleep(5);//等待数据缓冲好

                int count = mySerialPort.BytesToRead;

                byte[] buffer = new byte[count];

                mySerialPort.Read(buffer, 0, count);

                if (pushReceiveData != null)
                    pushReceiveData(buffer);
            }
            catch(Exception ex)
            { 

            }
        }

    }
}
